package utils;

import java.util.ArrayList;
import com.robotium.solo.Solo;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.SystemClock;
import android.test.InstrumentationTestCase;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import utils.MyException.NotFoundException;

/**
 * 工具类
 */
public class Util {
	public static final String TAG = "yiqijiao";

	/**
	 * 通过resourceID查找数字ID 获得控件 (主要使用在编写界面，获取界面控件时使用)
	 */
	@Deprecated
	public static View getViewFromID(String id, Activity activity) {
		// 获取包名
		String packageName = activity.getApplicationContext().getPackageName();
		// 把resourceId转换成数字ID
		int viewId = activity.getApplicationContext().getResources().getIdentifier(id, "id", packageName);
		// 获取控件
		return activity.findViewById(viewId);
	}

	/**
	 * 获取当前窗口可见的控件对象，为了节约测试时间和防止界面加载缓慢的问题，只重复搜索界面1次<br>
	 * 替换之前的获取控件的方法 <br>
	 * 
	 * @param solo
	 * @param id
	 *            StringID
	 * @param index
	 *            相同id存在多个控件，指定获取第几个，0标示第一个
	 * @return 如果窗口存在控件，则返回控件对象，否则返回null（这里如果控件不可见，则会返回null）
	 */
	@Deprecated
	public static View getViewFromID(Solo solo, String id, int index) {

		Activity activity = solo.getCurrentActivity();
		ArrayList<View> list_1 = new ArrayList<View>();
		ArrayList<View> list_2 = new ArrayList<View>();

		String packageName = activity.getApplicationContext().getPackageName();
		int viewId = activity.getApplicationContext().getResources().getIdentifier(id, "id", packageName);
		int num = 2;

		do {
			list_1 = solo.getCurrentViews();

			for (int i = 0; i < list_1.size(); i++) {
				if (viewId == list_1.get(i).getId() && list_1.get(i).isShown()) {
					list_2.add(list_1.get(i));
				}
			}

			if (list_2.size() > index) {
				return list_2.get(index);
			} else {
				list_1.clear();
				list_2.clear();
			}

			num--;

		} while (num > 0);

		return null;
	}

	/**
	 * 唤醒屏幕
	 * 使用uiautomator的wakeup方法替换
	 */
	@SuppressLint("Wakelock")
	@Deprecated
	public WakeLock wakeScreen(InstrumentationTestCase owner) {

		PowerManager pm = (PowerManager) owner.getInstrumentation().getTargetContext()
				.getSystemService(Context.POWER_SERVICE);

		WakeLock wakeLock = pm.newWakeLock(
				PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
				owner.getClass().getSimpleName());

		wakeLock.acquire();

		return wakeLock;
	}
	
	/**
	 * 简单比较2个bitmap，先对比宽度和高度，再对比每个像素点的颜色<br>
	 * 使用bitmap类中的sameAs方法比较2个bitmap对象，当前方法已过时<br>
	 * 
	 * @param bmp1
	 * @param bmp2
	 * @return boolean
	 */
	@Deprecated
	public boolean imageView_SameAs(Bitmap bmp1, Bitmap bmp2) {

		/*
		 * ImageView
		 * payed=(ImageView)solo.getView("cc.jishibang.bang.server:id/pay",0);
		 * ImageView unpay=(ImageView)
		 * solo.getView("cc.jishibang.bang.server:id/pay",1); ImageView
		 * unpay1=(ImageView)solo.getView("cc.jishibang.bang.server:id/pay",2);
		 * solo.clickOnView(payed); solo.goBack(); solo.sleep(1000);
		 * payed.setDrawingCacheEnabled(true);
		 * //通过imageview获取其图片对象，在调用该方法时，必须调用setDrawingCacheEnabled（true）
		 * 否则报空指针错误 Bitmap id=payed.getDrawingCache();
		 * 
		 * unpay.setDrawingCacheEnabled(true); Bitmap
		 * id1=unpay.getDrawingCache();
		 * 
		 * unpay1.setDrawingCacheEnabled(true); Bitmap
		 * bitmap=unpay1.getDrawingCache();
		 * 
		 * boolean bo=Util.compare2Image(id, id1); boolean
		 * bo1=Util.compare2Image(id1, bitmap);
		 * 
		 * payed.setDrawingCacheEnabled(false);//清空图像缓存，否则下一次获取的图片是上一次的图片
		 * unpay.setDrawingCacheEnabled(false);
		 * unpay1.setDrawingCacheEnabled(false);
		 */

		int iteration = 0;
		int width = bmp1.getWidth();
		int height = bmp1.getHeight();

		if (width != bmp2.getWidth())
			return false;
		if (height != bmp2.getHeight())
			return false;

		if (width < height) {
			iteration = width;
		} else {
			iteration = height;
		}
		for (int i = 0; i < iteration; ++i) {
			if (bmp1.getPixel(i, i) != bmp2.getPixel(i, i))
				return false;
		}
		return true;
	}

	/**
	 * 确定当前界面控件（可见）id及类型相同的控件的个数<br>
	 * 注：该方法应尽量使用在，界面编写界面，testcase中应尽量不用<br>
	 * 
	 * @param solo
	 * 
	 * @param id
	 *            String id
	 * @param clazz
	 *            该控件的类型字符串
	 * @return
	 */
	public int getNumeberOfSameID(Solo solo, String id, String clazz) {
		int viewsNumber = 0;
		Activity activity = solo.getCurrentActivity();
		String packageName = activity.getApplicationContext().getPackageName();
		// 把resourceId转换成数字ID
		// 只要“id”是正确的，就一定可以拿到他响应的数字id，因为数字ID都保存在R类中
		int viewId = activity.getApplicationContext().getResources().getIdentifier(id, "id", packageName);
		solo.sleep(2000);
		ArrayList<View> list = solo.getCurrentViews();

		for (int i = 0; i < list.size(); i++) {
			// view.isShown标示控件本身及其父类都是visible，才返回true。而view.getVisibility() ==
			// View.VISIBLE只是判断其本身是否可见
			if (viewId == list.get(i).getId() && list.get(i).getClass().getSimpleName().equals(clazz)
					&& list.get(i).isShown()) {
				Log.d(TAG, list.get(i).getClass().getSimpleName() + "====" + list.get(i).getId());
				viewsNumber++;
			}
		}
		return viewsNumber;
	}

	/**
	 * 
	 * 获取当前activity相同ID的控件个数,不可见的控件不会计算在内
	 * 
	 * @param solo
	 * @param id
	 *            String ID
	 * @param activity
	 *            当前活动
	 * @return 相同ID的控件个数
	 */
	public int getNumeberOfSameID(Solo solo, String id) {
		int viewsNumber = 0;
		Activity activity = solo.getCurrentActivity();
		String packageName = activity.getApplicationContext().getPackageName();
		// 把resourceId转换成数字ID
		// 只要“id”是正确的，就一定可以拿到他相应的数字id，因为数字ID是根据StringID自动生成-保存在R类中
		int viewId = activity.getApplicationContext().getResources().getIdentifier(id, "id", packageName);
		solo.sleep(2000);
		ArrayList<View> list = solo.getCurrentViews();

		for (int i = 0; i < list.size(); i++) {

			if (viewId == list.get(i).getId() && list.get(i).isShown()) {
				viewsNumber++;
			}
		}
		return viewsNumber;
	}

	/**
	 * 获取当前界面，多个相同ID的控件的最后1个控件对象
	 * 
	 * @param solo
	 * @param id
	 *            String ID
	 * @param activity
	 * @return
	 */
	public View getLastView(Solo solo, String id) {
		ArrayList<View> list_1 = new ArrayList<View>();
		ArrayList<View> list_2 = new ArrayList<View>();
		Activity activity = solo.getCurrentActivity();
		String packageName = activity.getApplicationContext().getPackageName();
		// 把resourceId转换成数字ID
		int viewId = activity.getApplicationContext().getResources().getIdentifier(id, "id", packageName);
		solo.sleep(2000);
		list_1 = solo.getCurrentViews();
		for (int i = 0; i < list_1.size(); i++) {

			if (viewId == list_1.get(i).getId()) {
				list_2.add(list_1.get(i));
			}
		}
		return list_2.get(list_2.size() - 1);
	}

	/**
	 * 获取指定父类控件下的，指定的子控件
	 * 
	 * @param solo
	 * @param childID
	 *            子控件ID
	 * @param parentID
	 *            父类控件ID
	 * @return 子控件对象
	 */
	public static View myGetView(Solo solo, String childID, String parentID) {
		long endTime = SystemClock.uptimeMillis() + 15000;
		Activity activity$;
		activity$ = solo.getCurrentActivity();

		ArrayList<? extends View> list_1 = new ArrayList<View>();
		ArrayList<View> list_2 = new ArrayList<View>();

		String packageName = activity$.getApplicationContext().getPackageName();
		// 把resourceId转换成数字ID
		int viewId = activity$.getApplicationContext().getResources().getIdentifier(childID, "id", packageName);
		do {
			// 获取指定父类控件下，指定类型的所有子控件
			list_1 = solo.getCurrentViews(solo.getView(childID).getClass(), solo.getView(parentID));
			// 遍历取出指定控件
			for (int i = 0; i < list_1.size(); i++) {

				if (viewId == list_1.get(i).getId() && list_1.get(i).isShown()) {
					list_2.add(list_1.get(i));
				}
			}
			if (list_2.size() > 0) {
				return list_2.get(0);
			} else {
				list_1.clear();
				list_2.clear();
			}
			if (SystemClock.uptimeMillis() >= endTime) {
				Log.e(TAG, "未发现目标控件");
				break;
			}
		} while (true);
		return null;
	}

	/**
	 * 获取指定父类下的指定子类控件
	 * 
	 * @param solo
	 * @param childID
	 * @param paView
	 * @return
	 */
	public static View myGetView(Solo solo, String childID, View paView) {
		long endTime = SystemClock.uptimeMillis() + 15000;
		Activity activity$;
		activity$ = solo.getCurrentActivity();

		ArrayList<? extends View> list_1 = new ArrayList<View>();
		ArrayList<View> list_2 = new ArrayList<View>();

		String packageName = activity$.getApplicationContext().getPackageName();
		// 把resourceId转换成数字ID
		int viewId = activity$.getApplicationContext().getResources().getIdentifier(childID, "id", packageName);
		do {
			// 获取指定父类控件下，指定类型的所有子控件
			list_1 = solo.getCurrentViews(solo.getView(childID).getClass(), true, paView);
			// 遍历取出指定控件
			for (int i = 0; i < list_1.size(); i++) {

				if (viewId == list_1.get(i).getId() && list_1.get(i).isShown()) {
					list_2.add(list_1.get(i));
				}
			}
			if (list_2.size() > 0) {
				return list_2.get(0);
			} else {
				list_1.clear();
				list_2.clear();
			}
			if (SystemClock.uptimeMillis() >= endTime) {
				Log.e(TAG, "未发现目标控件");
				break;
			}
		} while (true);
		return null;
	}

	/**
	 * 获取指定父类控件下的，指定位置的子控件
	 * 
	 * @param solo
	 * @param childID
	 *            要获取的子类控件ID
	 * @param parentID
	 *            要所搜的父类控件ID
	 * @param index
	 *            要获取第几个子类控件
	 * @return 相应位置的子类控件对象
	 */
	public static View myGetView(Solo solo, String childID, String parentID, int index) {
		long endTime = SystemClock.uptimeMillis() + 15000;
		Activity activity$;
		activity$ = solo.getCurrentActivity();

		ArrayList<? extends View> list_1 = new ArrayList<View>();
		ArrayList<View> list_2 = new ArrayList<View>();

		String packageName = activity$.getApplicationContext().getPackageName();
		// 把resourceId转换成数字ID
		int viewId = activity$.getApplicationContext().getResources().getIdentifier(childID, "id", packageName);
		do {
			// 获取指定父类控件下，指定类型的所有子控件
			list_1 = solo.getCurrentViews(solo.getView(childID).getClass(), solo.getView(parentID));
			// 遍历取出指定控件
			for (int i = 0; i < list_1.size(); i++) {

				if (viewId == list_1.get(i).getId() && list_1.get(i).isShown()) {
					list_2.add(list_1.get(i));
				}
			}
			if (list_2.size() > index) {
				return list_2.get(index);
			} else {
				list_1.clear();
				list_2.clear();
			}
			if (SystemClock.uptimeMillis() >= endTime) {
				Log.e(TAG, "未发现目标控件");
				break;
			}
		} while (true);
		return null;
	}

	/**
	 * 获取当前界面相同ID的控件中的某一个，可以自定义超时时间
	 * 
	 * @param solo
	 * @param id
	 * @param index
	 *            获取第几个控件 ，从0开始
	 * @param times
	 *            自定义超时时间
	 * @return
	 */
	public static View myGetView(Solo solo, String id, int index, int times) {
		long endTime = SystemClock.uptimeMillis() + times;

		ArrayList<View> list_1 = new ArrayList<View>();
		ArrayList<View> list_2 = new ArrayList<View>();

		Activity activity$ = solo.getCurrentActivity();
		String packageName = activity$.getApplicationContext().getPackageName();
		int viewId = activity$.getApplicationContext().getResources().getIdentifier(id, "id", packageName);

		do {
			list_1 = solo.getCurrentViews();// 获取当前窗口，可见的所有控件
			for (int i = 0; i < list_1.size(); i++) {

				if (viewId == list_1.get(i).getId() && list_1.get(i).isShown()) {
					list_2.add(list_1.get(i));
				}
			}
			if (list_2.size() > index) {
				return list_2.get(index);
			} else {
				list_1.clear();
				list_2.clear();
			}
			if (SystemClock.uptimeMillis() >= endTime) {
				Log.e(TAG, "未发现目标控件++");
				break;
			}
		} while (true);
		return null;
	}

	/**
	 * 获取第一个控件。
	 * 
	 * @param solo
	 * @param id
	 * @return 目标控件
	 */
	public static View myGetView(Solo solo, String id) {
		View view = myGetView(solo, id, 0, 15000);
		return view;
	}

	/**
	 * 获取指定index获取控件。默认等待最多15s
	 * 
	 * @param solo
	 * @param id
	 * @param index
	 * @return
	 * @throws NotFoundException
	 */
	public static View myGetView(Solo solo, String id, int index) throws NotFoundException {

		View view = myGetView(solo, id, index, 15000);

		return view;
	}

	/**
	 * 获取含有指定文本的父类控件
	 * 
	 * @param solo
	 * @param id
	 *            控件ID
	 * @param text
	 *            控件中包含的文本
	 * @return
	 * @throws NotFoundException
	 */
	public static View myGetFatherView(Solo solo, String id, String text) {

		long endTime = SystemClock.uptimeMillis() + 15000;
		Activity activity$;
		activity$ = solo.getCurrentActivity();

		ArrayList<View> list_1 = new ArrayList<View>();
		ArrayList<View> list_2 = new ArrayList<View>();

		String packageName = activity$.getApplicationContext().getPackageName();
		// 把resourceId转换成数字ID
		int viewId = activity$.getApplicationContext().getResources().getIdentifier(id, "id", packageName);
		do {
			list_1 = solo.getViews();// 获取当前窗口，可见的所有控件
			for (int i = 0; i < list_1.size(); i++) {

				if (viewId == list_1.get(i).getId() && list_1.get(i).isShown()) {
					list_2.add(list_1.get(i));
				}
			}
			if (list_2.size() != 0) {
				for (View view : list_2) {

					if (viewContainsText(solo, view, text)) {
						return view;
					}
				}
			} else {
				solo.scrollDown();
				Log.w(TAG, "scrollDown+滑动列表再查找：" + solo.scrollDown());
			}
			if (SystemClock.uptimeMillis() >= endTime) {
				Log.e(TAG, "未发现目标控件++");
				break;
			}
		} while (true);
		return null;
	}

	/**
	 * 判断某组件下（父控件）中的某个子控件（必须是textview）显示的文本是否包含指定文本
	 * 
	 * @param solo
	 * @param view
	 *            父控件
	 * @param text
	 *            需要验证的文本
	 * @return
	 */
	public static boolean viewContainsText(Solo solo, View view, String text) {
		ArrayList<View> arrayList = solo.getViews(view);

		for (View mview : arrayList) {

			if (mview instanceof TextView) {
				if (((TextView) mview).getText().toString().equals(text)) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 判断某组件下（父控件）中是否包含指定文本
	 * 
	 * @param solo
	 * @param id
	 *            控件id
	 * @param text
	 *            判断的文本
	 * @return
	 * @throws NotFoundException
	 */
	public static boolean viewContainsText(Solo solo, String id, String text) throws NotFoundException {
		ArrayList<View> arrayList = solo.getViews(myGetView(solo, id));

		for (View mview : arrayList) {

			if (mview instanceof TextView) {
				if (((TextView) mview).getText().toString().equals(text)) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 界面上是否存在目标控件
	 * 
	 * @param solo
	 * @param String
	 *            传入id
	 * @return boolean
	 * @throws NotFoundException
	 * @throws Exception
	 */
	public boolean isVisibleOfViews(Solo solo, String id) {
		long endTime = SystemClock.uptimeMillis() + 15000;
		Activity activity = solo.getCurrentActivity();

		String packageName = activity.getApplicationContext().getPackageName();
		// 把resourceId转换成数字ID
		int viewId = activity.getApplicationContext().getResources().getIdentifier(id, "id", packageName);
		do {
			if (SystemClock.uptimeMillis() >= endTime) {
				Log.e(TAG, "未找到目标控件");
				break;
			}
			ArrayList<View> views = solo.getCurrentViews();
			for (View view : views) {
				if (view.getId() == viewId && view.isShown()) {// 且必须可见的才表示存在
					return true;
				}
			}
		} while (true);
		return false;
	}

	/**
	 * 界面上是否存在目标控件，不可见的控件不会计算在内
	 * 
	 * @param solo
	 * @param view
	 *            传入view控件，通过int id判断是否存在控件
	 * @return
	 */
	public boolean isVisibleOfViews(Solo solo, View view) {
		long endTime = SystemClock.uptimeMillis() + 15000;

		do {
			if (SystemClock.uptimeMillis() >= endTime) {
				Log.e(TAG, "未找到目标控件");
				break;
			}
			ArrayList<View> views1 = solo.getCurrentViews();
			for (View view1 : views1) {
				if (view1.getId() == view.getId() && view1.isShown()) {// 且必须可见的才表示存在
					return true;
				}
			}
		} while (true);
		return false;
	}

	/**
	 * 获取界面的toast文本内容.默认toast的id为android:id/message，如果无法获取请先确定ID是否正确
	 * 
	 * @return
	 */
	public String getToastText(Solo solo) {
		String toastString = null;
		long endTime = SystemClock.uptimeMillis() + 3000;

		do {
			TextView toastText = (TextView) myGetView(solo, "android:id/message", 0, 0);
			if (toastText != null) {
				toastString = toastText.getText().toString();
				return toastString;
			}
			if (SystemClock.uptimeMillis() > endTime) {
				break;
			}
		} while (true);
		return toastString;
	}
}
